
import { regular, asyncValTypes } from './regular'
// 设置自定义验证
function getValidateFun (type, msg, pattern) {
    const checkType = regular[type]
    if (checkType === undefined && type !== 'custom_regular') {
        return null
    }
    const isvalidate = (rule, value, callback) => {
        if (value !== null && value !== '') {
            // 自定义正则表达式进行验证
            if (type === 'custom_regular') {
                if (pattern !== undefined && !pattern.test(value)) {
                    callback(new Error(msg))
                } else {
                    callback()
                }
            // 否则去匹配设定的类型
            } else {
                if (!checkType.test(value)) {
                    callback(new Error(msg))
                } else {
                    callback()
                }
            }
        } else {
            callback()
        }
    }
    return isvalidate
}
// 创建表单数据
const creadFormData = (formData) => {
    const rules = {}
    const form = {}
    for (let i = 0; i < formData.length; i++) {
        const item = formData[i]
        form[item.prop] = item.value
        const tempRule = []
        for (let j = 0; j < item.rules.length; j++) {
            const rulesType = item.rules[j].type
            if (rulesType) {
                const valiDateFun = getValidateFun(rulesType, item.rules[j].message, item.rules[j].pattern)
                if (valiDateFun) { // 匹配到自定义类型就将自定义类型设置进去
                    tempRule.push({ validator: valiDateFun, trigger: item.rules[j].trigger })
                } else if (asyncValTypes.includes(rulesType)) { // 没有匹配到自定义的类型  但是此类型输入内置类型 那么也设置进去
                    tempRule.push(item.rules[j])
                }
            } else {
                tempRule.push(item.rules[j])
            }
        }
        rules[item.prop] = tempRule
    }
    return { rules, form }
}

export {
    creadFormData
}
